﻿using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfaces;
using B.S.BasicData.Write.Api.Application.Command.W;
using MediatR;
using Microsoft.IdentityModel.Tokens;

namespace B.S.BasicData.Write.Api.Application.CommandHandler.W
{
    /// <summary>
    /// 显示发货运单
    /// </summary>
    public class ShowPendingShipmentWaybillsCommandHander : IRequestHandler<ShowPendingShipmentWaybillsCommand, ApiPaging<PendingShipmentWaybillsModel>>
    {
        /// <summary>
        /// 发货运单仓储
        /// </summary>
        private readonly IBaseRepository<PendingShipmentWaybillsModel> _pendingShipmentWaybillsModelRequest;

        public ShowPendingShipmentWaybillsCommandHander(IBaseRepository<PendingShipmentWaybillsModel> pendingShipmentWaybillsModelRequest)
        {
            _pendingShipmentWaybillsModelRequest = pendingShipmentWaybillsModelRequest;
        }


        /// <summary>
        /// 显示发货运单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiPaging<PendingShipmentWaybillsModel>> Handle(ShowPendingShipmentWaybillsCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<PendingShipmentWaybillsModel> res = new ApiPaging<PendingShipmentWaybillsModel>();
            var pendingShipmentWaybillsModels= _pendingShipmentWaybillsModelRequest.GetAll();

            if (!string.IsNullOrEmpty(request.OutboundOrderNumber)) 
            {
                pendingShipmentWaybillsModels = pendingShipmentWaybillsModels.Where(a=>a.OutboundOrderNumber.Contains(request.OutboundOrderNumber));
            }
            if (!string.IsNullOrEmpty(request.States))
            {
                pendingShipmentWaybillsModels = pendingShipmentWaybillsModels.Where(a=>a.States==request.States);
            }
            res.TotalCount = pendingShipmentWaybillsModels.Count();
            res.TotalPage= (int)Math.Ceiling(pendingShipmentWaybillsModels.Count() * 1.0 / request.PageSize);
            res.Items = pendingShipmentWaybillsModels.OrderByDescending(a=>a.Id).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
            return Task.FromResult(res);
        }
    }
}
